/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "GL/glew.h"
#include "fr_local.h"
#include "gl_local.h"
#include <algorithm>

/*-----------------------------------------------------------------------------
	GFX
-----------------------------------------------------------------------------*/

//
//	EFRGFX::EFRGFX
//
EFRGFX::EFRGFX( EFRGFXSystem *gfxs )
{
	this->gfxsys	=	gfxs;
	SetTexture("*white", RS_GFX_NORMAL);
}


//
//	EFRGFX::~EFRGFX
//
EFRGFX::~EFRGFX( void )
{

}


//
//	EFRGFX::AllocSprites
//
void EFRGFX::AllocSprites( uint num )
{
	quads.resize( num );
}


//
//	EFRGFX::SetTexture
//
void EFRGFX::SetTexture( const EString &texname, ERSGFXBlend blend )
{
	texture			=	gfxsys->scene->txm->RegisterTexture( texname );
	this->blend		=	blend;
}


//
//	EFRGFX::SetColor
//
void EFRGFX::SetColor( uint sprite_id, const EColor &color )
{
	ASSERT( sprite_id < quads.size() );
	quads[ sprite_id ].color	=	color;
}


//
//	EFRGFX::SetVertices
//
void EFRGFX::SetVertices( uint sprite_id, const EPoint *vertices, const ETexCoord *uvs0, const ETexCoord *uvs2 )
{
	ASSERT( sprite_id < quads.size() );
	for (uint i=0; i<4; i++) {
		quads[ sprite_id ].verts[i]	=	vertices[i];
		quads[ sprite_id ].uvs0[i]	=	uvs0[i];
		quads[ sprite_id ].uvs1[i]	=	uvs2[i];
	}
}


//
//	EFRGFX::AimToCamera
//
void EFRGFX::AimToCamera( uint sprite_id, const EPoint &origin, float size, float angle, float aspect )
{
	ASSERT( sprite_id < quads.size() );
	EMatrix	vm	=	gfxsys->scene->view.matrix_view;
	EVector		ax	=	EVector( size * vm(0,0), size * vm(1,0), size * vm(2,0) );
	EVector		ay	=	EVector( size * vm(0,1), size * vm(1,1), size * vm(2,1) );
	
	float	c		=	cos( angle );
	float	s		=	sin( angle );
	
	quads[ sprite_id ].verts[0]	=	origin + ( ax * c + ay * s );
	quads[ sprite_id ].verts[1]	=	origin - ( ax * s + ay * c );
	quads[ sprite_id ].verts[2]	=	origin - ( ax * c - ay * s );
	quads[ sprite_id ].verts[3]	=	origin + ( ax * s - ay * c );
}


//
//	EFRGFX::SetCrossFade
//
void EFRGFX::SetCrossFade( uint sprite_id, float xfade )
{
	ASSERT( sprite_id < quads.size() );
	quads[ sprite_id ].xfade	=	xfade;
}


//
//	EFRGFX::SetVisible
//
void EFRGFX::SetVisible( uint sprite_id, bool visible )
{
	ASSERT( sprite_id < quads.size() );
	quads[ sprite_id ].visible	=	visible;
}


//
//	EFRGFX::Render
//
void EFRGFX::Render( IPxEffect effect )
{
	switch (blend) {
		case RS_GFX_NORMAL		:  effect->SetTechnique("tech_gfx_normal");			break;
		/*case RS_GFX_ADDITIVE	:  effect->SetTechnique("tech_gfx_additive");		break;
		case RS_GFX_SUBTRACTIVE	:  effect->SetTechnique("tech_gfx_subtractive");	break;
		case RS_GFX_MULTIPLY	:  effect->SetTechnique("tech_gfx_multiply");		break;
		case RS_GFX_LIGHTEN		:  effect->SetTechnique("tech_gfx_lighten");		break;
		case RS_GFX_DISTORTIVE	:  effect->SetTechnique("tech_gfx_distortive");		break;*/
	}

	EMatrix	v	=	gfxsys->scene->view.matrix_view;
	EMatrix	p	=	gfxsys->scene->proj.matrix_proj;

	effect->SetUniform( "matrix_wvp", v * p );
	effect->SetTexture( "texture0", texture );

	uint n;
	effect->Begin( n );
	
	for (uint i=0; i<n; i++) {
		effect->BeginPass(i);
		
		DrawQuads();	
		
		effect->EndPass();
	}
	
	effect->End();
}


//
//	EFRGFX::DrawQuad
//
void EFRGFX::DrawQuads( void )
{
#if 0
	glBegin( GL_QUADS );
	
		for (uint i=0; i<quads.size(); i++) {
		
			Quad *q = &quads[i];
			
			if (!q->visible) {
				continue;
			}
	
			for (uint j=0; j<4; j++) {
				glMultiTexCoord2fv	( GL_TEXTURE0, q->uvs0[j].Ptr() );
				glMultiTexCoord2fv	( GL_TEXTURE1, q->uvs1[j].Ptr() );
				glMultiTexCoord1f	( GL_TEXTURE2, q->xfade );
				glColor4fv			( q->color.v );
				glVertex3f			( q->verts[j].x, q->verts[j].y, q->verts[j].z );
			}	
		}
	
	glEnd();
#else
	std::vector<GLfloat> vertices(quads.size()*4*3);
	std::vector<GLfloat> colors(quads.size()*4*4);
	std::vector<GLfloat> uvs0(quads.size()*4*2);
	std::vector<GLfloat> uvs1(quads.size()*4*2);
	std::vector<GLfloat> uvs2(quads.size()*4);

	GLfloat *color_p = &colors[0];
	GLfloat *vert_p  = &vertices[0];
	GLfloat *uvs0_p  = &uvs0[0];
	GLfloat *uvs1_p  = &uvs1[0];
	GLfloat *uvs2_p  = &uvs2[0];

	for (uint i=0; i<quads.size(); i++) {
		
			Quad *q = &quads[i];
			
			if (!q->visible) {
				continue;
			}
	
			for (uint j=0; j<4; j++) {
				memcpy( color_p, q->color.v,		4*sizeof(GLfloat) );	color_p += 4;
				memcpy( vert_p,  q->verts[j].v,		3*sizeof(GLfloat) );	vert_p  += 3;
				memcpy( uvs0_p,  q->uvs0[j].Ptr(),	2*sizeof(GLfloat) );	uvs0_p  += 2;
				memcpy( uvs1_p,  q->uvs1[j].Ptr(),	2*sizeof(GLfloat) );	uvs1_p  += 2;
				*(uvs2_p++) = q->xfade;
			}	
	}

	glClientActiveTexture( GL_TEXTURE0);	
		glTexCoordPointer( 2, GL_FLOAT, 0, &uvs0[0]); 
		GL_CALL( glEnableClientState(GL_TEXTURE_COORD_ARRAY) );

	glClientActiveTexture( GL_TEXTURE1);	
		glTexCoordPointer( 2, GL_FLOAT, 0, &uvs1[0]); 
		GL_CALL( glEnableClientState(GL_TEXTURE_COORD_ARRAY) );

	glClientActiveTexture( GL_TEXTURE2);	
		glTexCoordPointer( 1, GL_FLOAT, 0, &uvs2[0]); 
		GL_CALL( glEnableClientState(GL_TEXTURE_COORD_ARRAY) );

	GL_CALL( glVertexPointer( 3, GL_FLOAT, 0, &vertices[0] ) );
	GL_CALL( glColorPointer(  4, GL_FLOAT, 0, &colors[0]   ) );

	GL_CALL( glEnableClientState(GL_VERTEX_ARRAY) );
	GL_CALL( glEnableClientState(GL_COLOR_ARRAY) );


	GL_CALL( glDrawArrays(GL_QUADS, 0, quads.size()*4) );

	// deactivate vertex arrays after drawing
	GL_CALL( glDisableClientState(GL_COLOR_ARRAY) );
	GL_CALL( glDisableClientState(GL_VERTEX_ARRAY) );


	glClientActiveTexture( GL_TEXTURE2);
		GL_CALL( glDisableClientState(GL_TEXTURE_COORD_ARRAY) );
	glClientActiveTexture( GL_TEXTURE1);
		GL_CALL( glDisableClientState(GL_TEXTURE_COORD_ARRAY) );
	glClientActiveTexture( GL_TEXTURE0);
		GL_CALL( glDisableClientState(GL_TEXTURE_COORD_ARRAY) );
	
	vertices.clear();
	colors.clear();
	uvs0.clear();
	uvs1.clear();
	uvs2.clear();	
	
#endif
}

